package com.soshalboard.utils;



import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HTTPConnection {

	private HttpClient httpClient = null;
	private static Log log = LogFactory.getLog(HTTPConnection.class);	

	public HTTPConnection(){

	}	

	public HTTPConnection(String maxConnection, String maxTotalConnection){
		MultiThreadedHttpConnectionManager connectionMgr = new MultiThreadedHttpConnectionManager();
		connectionMgr.getParams().setMaxConnectionsPerHost(new HostConfiguration(),Integer.valueOf(maxConnection));
		connectionMgr.getParams().setMaxTotalConnections(Integer.valueOf(maxTotalConnection));		
		httpClient = new HttpClient(connectionMgr);
	}

	public HttpClient getHttpClient() {
		return httpClient;
	}

	public String get(String url) {
		URI uri = null;
		try {
			uri = new URI(url, false);
		} catch (Exception e2) {
			log.info("URI Exception", e2);
		}

		GetMethod get = new GetMethod(url);
		log.info("URL submitted on Get:" + url);

		get.setFollowRedirects(false);

		String responseStr = "";
		try {
			int iGetResultCode = httpClient.executeMethod(get);

			if (200 == iGetResultCode) {
				responseStr = get.getResponseBodyAsString();
			} else {
				log.info("Couldnot connect , error is " + iGetResultCode);
			}
		} catch (Exception e) {
			log.error("Issues with Request " + e);
		} finally {
			get.releaseConnection();
		}

		return responseStr;
	}

	public InputStream getBinary(String url) {
		URI uri=null;
		try {
			uri = new URI(url, false);
		} catch (Exception e) {
			log.error("URI Exception",e);
		}

		GetMethod get = new GetMethod(url);
		get.setFollowRedirects(false);

		InputStream is = null;
		try {
			int iGetResultCode = httpClient.executeMethod(get);

			if (200 == iGetResultCode) {
				byte [] response = get.getResponseBody();
				is = new ByteArrayInputStream(response);
			} else {
				log.info("Could not connect , error is " + iGetResultCode);
			}
		} catch (Exception e) {
			log.error("Issues with Request " + e);
		}finally {
			get.releaseConnection();
		}    	

		return is;		
	}	

	public String post (String url, InputStream body, Map<String, String> headers, Map<String, String> params) {

		url = makeUrl (url, params);

		final PostMethod filePost = new PostMethod( url);

		try
		{
			filePost.setRequestBody(body);
			
			if (null != headers) {
				Iterator it = headers.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry pairs = (Map.Entry)it.next();
					filePost.addRequestHeader(pairs.getKey().toString(), pairs.getValue().toString());
				}
			}

			try {
				int status = httpClient.executeMethod( filePost );
				return filePost.getResponseBodyAsString();
			} catch (Exception e) {
				log.error("Exception Ocurred ",e);
			}
		}finally {
			filePost.releaseConnection();
		}
		return "";
	}

	public void delete (String url) {
		final DeleteMethod delete = new DeleteMethod (url);

		try {
			int status = httpClient.executeMethod( delete );
		} catch (Exception e) {
			log.error("Exception Ocurred ",e);
		}finally {
			delete.releaseConnection();
		}
	}

	private String makeUrl(String url, Map<String, String> parameters) {
		boolean and = url.indexOf("?") != -1;
		if (parameters != null) {
			for (Map.Entry<String, String> param : parameters.entrySet()) {
				try {
					url += (and ? "&" : "?") + param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8");
					and = true;
				} catch (Exception e) {
					log.error("Exception Ocurred ",e);
				}
			}
		}
		return url;
	}	
}